import 'package:flutter_tts/flutter_tts.dart';

import 'dart:async';
import 'dart:io';

/// Singleton tool class for tts

/// Use TtsHelper step:
///
/// Method : #isLanguageAvailable judge language, here language is _languageMap's values like "en-US",instead of the type of 'en' etc..
///
/// Method : #getTtsLanguage  help you convert "en" to "en-US".
///
/// Method : #setLanguage help you set Language , but "en-US" is default value
///
/// use example:
/// TtsHelper.instance.speak("speech content");
/// or
/// TtsHelper.instance.setLanguageAndSpeak("speech content", "en-US");
/// ...
class TtsHelper {
  TtsHelper._();

  static final TtsHelper _manager = TtsHelper._();

  factory TtsHelper() {
    return _manager;
  }

  late FlutterTts flutterTts;

  Future initTTS() async {
    flutterTts = FlutterTts();

    // await flutterTts.awaitSpeakCompletion(true);

    // await flutterTts.awaitSynthCompletion(true);
    // 设置语言
    await flutterTts.setLanguage("zh-CN");

    // 设置音量
    await flutterTts.setVolume(1);

    // 设置语速
    await flutterTts.setSpeechRate(0.5);

    // 音调
    await flutterTts.setPitch(1.0);
  }



  Future speak(String text) async {
    await stop();

    if (text.isNotEmpty) {
      await flutterTts.speak(text);
    }
  }

  /// 暂停
  Future pause() async {
    await flutterTts.pause();
  }

  /// 结束
  Future stop() async {
    await flutterTts.stop();
  }
}